/*
 * @Author: 李一番 
 * @Date: 2023-01-08 20:34:26 
 * @Last Modified by: 李一番
 * @Last Modified time: 2023-01-08 20:49:58
 */

/**
 * @description 接口请求封装
 */

import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig, AxiosRequestHeaders, AxiosResponse } from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

interface IResponse<T = any> {
  code: string
  msg: string
  data?: T
  config?: any
}
const service: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
  withCredentials: true,
  timeout: 60000,
})

service.interceptors.request.use((config: AxiosRequestConfig) => {
  Object.assign(config.headers as AxiosRequestHeaders, {
    'Accept': 'application/json,text/javascript, */*; q=0.01',
    'X-Requested-With': 'XMLHttpRequest'
  })
  return config
}, (err: any) => {
  return Promise.reject(err)
})
service.interceptors.response.use((response: AxiosResponse<any, any>) => {
  const {
    config: { responseType },
    data
  } = response as unknown as IResponse;
  const { code, msg } = data;
  if (`${code}` === '0') { 
    return data
  } else {
    ElMessage.error({ message: msg, showClose: true });
    return data;
  }
}, err => {
  ElMessage.error({ message: err, showClose: true });
  return Promise.reject(err)
})

export default service
